package com.binvshe.binvshe.organization;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.binvshe.binvshe.R;
import com.binvshe.binvshe.account.Account;
import com.binvshe.binvshe.common.http.DataRequestListener;
import com.binvshe.binvshe.common.http.MyHttpRequest;
import com.binvshe.binvshe.common.http.UrlCenter;
import com.binvshe.binvshe.common.image.IML;
import com.binvshe.binvshe.mine.usercenter.UserCenterActivity;
import com.binvshe.binvshe.opus.OpusDetailsNewAcitvity;
import com.binvshe.binvshe.organization.entity.OpusListEntity;
import com.binvshe.binvshe.organization.tag.TagBean;
import com.pachong.android.baseuicomponent.adapter.RecyclerViewBaseAdapter;
import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.frameworkbase.utils.DateTimeUtil;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by Zoi.
 * E-mail：KyluZoi@gmail.com
 * 2016/9/13
 */
public class OpusAdapter extends RecyclerViewBaseAdapter<OpusListEntity> {

    public enum JBulderType {
        SHARE,//推荐
        DELETE//删除
    }

    private Activity mActivity;

    private JBulderType mJBulderType = null;

    public OpusAdapter(Context con) {
        super(con);
    }

    public OpusAdapter(Activity activity) {
        super(activity);
        mActivity = activity;
    }

    @Override
    public RecyclerView.ViewHolder onCreateHolder(ViewGroup parent, int viewType) {
        View view = ((LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.item_home_content, parent, false);
        return new OpusHolder(view);
    }

    public Activity getActivity() {
        return mActivity;
    }

    public void setActivity(Activity activity) {
        mActivity = activity;
    }


    @Override
    public void onBindHolder(RecyclerView.ViewHolder holder, int position) {
        OpusHolder mholder = (OpusHolder) holder;
        final OpusListEntity data = getData().get(position);
        mholder.mLnlytImage.removeAllViews();
        mholder.mTflytContentTag.removeAllViews();
        //<code> 加载image信息 </code>
        int i = 0;//foreach没有索引，自己创建索引
        for (OpusListEntity.ImagesEntity imagesEntity : data.getImages()) {

            if (i < 4) {
                if(i==data.getImages().size()-1|| i == 3){
                    RelativeLayout relativeLayout = new RelativeLayout(getContext());
                    RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                            RelativeLayout.LayoutParams.MATCH_PARENT);

                    RelativeLayout.LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(getImageSize(), getImageSize());
                    layoutParams.setMargins(0, 0, getContext().getResources().getDimensionPixelOffset(R.dimen.space_lv1), 0);
                    relativeLayout.setLayoutParams(layoutParams);
                    ImageView imageView = new ImageView(getContext());
                    TextView textView = new TextView(getContext());
                    imageView.setLayoutParams(rl);
                    textView.setLayoutParams(layoutParams1);
                    layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                    layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                    textView.setTextColor(Color.WHITE);
                    relativeLayout.addView(imageView);
                    relativeLayout.addView(textView);
                    IML.load(getContext(), imageView, imagesEntity.getUrl());
                    textView.setText("共"+data.getImages().size()+"张");
                    textView.setTextSize(10);
                    textView.setBackgroundResource(R.drawable.home_list_shape);
                    mholder.mLnlytImage.addView(relativeLayout, layoutParams);

                }else {
                    ImageView imageView = new ImageView(getContext());
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(getImageSize(), getImageSize());
                    layoutParams.setMargins(0, 0, getContext().getResources().getDimensionPixelOffset(R.dimen.space_lv1), 0);
                    imageView.setLayoutParams(layoutParams);
                    IML.load(getContext(), imageView, imagesEntity.getUrl());
                    mholder.mLnlytImage.addView(imageView);
                }
            } else {
                break;
            }
            i++;
        }
        //<code>加载标签信息</code>
        TagAdapter adaptet = getTagAdapter(data.getTags());
        mholder.mTflytContentTag.setAdapter(adaptet);
        adaptet.notifyDataChanged();
        //<code>加载用户以及内容信息</code>
        Account userEntity = data.getUser();
        IML.load(getContext(), mholder.mCivUserHead, userEntity.getPortrait());
        mholder.mCivUserHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UserCenterActivity.start(getContext(), data.getUser().getUserId());
            }
        });
        mholder.mTvUserName.setText(userEntity.getNickName());
//        if (data.getClub() != null) {//作品所在社团
//            setText(mholder.mTvUserOrg, data.getClub().getName());
//        }
        if (userEntity.getClub() != null) {//用户所在社团
            setText(mholder.mTvUserOrg, userEntity.getClub().getName());
        } else {
            setText(mholder.mTvUserOrg, "");
        }
        setText(mholder.mTvContentTitle, data.getTitle());
        setText(mholder.mTvContentDesc, data.getContent());
        String date = DateTimeUtil.getDateStr(new Date(Long.parseLong(data.getCreate_time())));
        setText(mholder.mTvOpusCreateTime, date);
        setText(mholder.mTvCommentNum, data.getComment_count() + "");
        setText(mholder.mTvZanNum, data.getLike_count() + "");
        if (getJBulderType() != null) {
            mholder.mBtnMore.setVisibility(View.VISIBLE);
            mholder.mBtnMore.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switch (getJBulderType()) {
                        case DELETE:
                            buildJump(v, new JumpWindowView.OnFlipClickListener() {
                                @Override
                                public void onItemClick(int position) {
                                    deleteArticle(data.getId());
                                }

                                @Override
                                public void dismiss() {

                                }
                            });
                            break;
                        case SHARE:
                            buildJump(v, new JumpWindowView.OnFlipClickListener() {
                                @Override
                                public void onItemClick(int position) {
                                    recommend(data.getId());
                                }
                                @Override
                                public void dismiss() {
                                }
                            });
                            break;
                    }
                }
            });
        } else {
            mholder.mBtnMore.setVisibility(View.GONE);
        }
        setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                OpusDetailsNewAcitvity.start(getContext(), getData().get(position).getId());
            }
        });
    }

    private void buildJump(View v, JumpWindowView.OnFlipClickListener onFlipClickListener) {
        switch (getJBulderType()) {
            case DELETE:
                JumpWindowHelper.jumpDelete(mActivity, v).create().setOnFlipClickListener(onFlipClickListener);
                break;
            case SHARE:
                JumpWindowHelper.jumpShare(mActivity, v).create().setOnFlipClickListener(onFlipClickListener);
                break;
        }
    }

    private void setText(TextView view, String content) {
        if (TextUtils.isEmpty(content)) {
            return;
        }
        view.setText(content);
    }

    public JBulderType getJBulderType() {
        return mJBulderType;
    }

    public void setJBulderType(JBulderType JBulderType) {
        mJBulderType = JBulderType;
    }


    /**
     * 得到 tag 的Adapter
     */
    private TagAdapter getTagAdapter(final List<TagBean> tagDatas) {
        TagAdapter adapter = new TagAdapter<TagBean>(tagDatas) {
            @Override
            public int getCount() {
                return tagDatas.size() < 6 ? tagDatas.size() : 5;
            }

            @Override
            public View getView(FlowLayout parent, int position, TagBean o) {
                View view = ((LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.item_tag, parent, false);
                TextView tvTagDel = (TextView) view.findViewById(R.id.tvTagDel);
                TextView tvTag = (TextView) view.findViewById(R.id.tvTag);
                o.setPositon(position);
                tvTag.setText(o.getTagContent());
                o.getTagBackGround(tvTag);
                tvTag.setTextColor(o.getTagTextColor());
                return view;
            }
        };
        return adapter;
    }


    /**
     * 获取图片高宽，屏幕高度减去padding 4等分
     *
     * @return
     */
    private int getImageSize() {
        float parentSpace = getContext().getResources().getDimensionPixelOffset(R.dimen.space_lv5) * 2;
        float subSpace = getContext().getResources().getDimensionPixelOffset(R.dimen.space_lv1) * 4;
        WindowManager wm = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        int width = (int) (wm.getDefaultDisplay().getWidth() - (parentSpace + subSpace));
        return width / 4;
    }

    public class OpusHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.civUserHead)
        CircleImageView mCivUserHead;
        @Bind(R.id.tvUserName)
        TextView mTvUserName;
        @Bind(R.id.tvUserOrg)
        TextView mTvUserOrg;
        @Bind(R.id.btnMore)
        ImageView mBtnMore;
        @Bind(R.id.tvContentTitle)
        TextView mTvContentTitle;
        @Bind(R.id.tvContentDesc)
        TextView mTvContentDesc;
        @Bind(R.id.lnlytImage)
        LinearLayout mLnlytImage;
        @Bind(R.id.tflytContentTag)
        TagFlowLayout mTflytContentTag;
        @Bind(R.id.tvOpusCreateTime)
        TextView mTvOpusCreateTime;
        @Bind(R.id.tvZanNum)
        TextView mTvZanNum;
        @Bind(R.id.tvCommentNum)
        TextView mTvCommentNum;

        public OpusHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }


    /**
     * 推荐作品请求
     */
    private void recommend(int articleID) {
        IHttpRequest request = new MyHttpRequest(getContext());
        String url = String.format(UrlCenter.RECOMMEND, articleID + "");
        request.put(url, null, new DataRequestListener(String.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(Object o) {
                Toast.makeText(getContext(), "推荐成功", Toast.LENGTH_SHORT).show();
                super.onSuccess(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    /**
     * 删除作品请求
     */
    private void deleteArticle(int articleID) {
        IHttpRequest request = new MyHttpRequest(getContext());
        String url = String.format(UrlCenter.DELETE_ARTICLE, articleID + "");
        request.delete(url, new UrlParams(), new DataRequestListener(String.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(Object o) {
                Toast.makeText(getContext(), ("删除成功"), Toast.LENGTH_SHORT).show();
                super.onSuccess(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }
}
